document.addEventListener('DOMContentLoaded', function() {
  const importForm = document.getElementById('importForm');
  const importResult = document.getElementById('importResult');
  if (importForm) {
    importForm.onsubmit = async function(e) {
      e.preventDefault();
      importResult.innerHTML = '';
      const table = document.getElementById('importTable').value;
      const fileInput = document.getElementById('importFile');
      if (!table) {
        importResult.innerHTML = '<span style="color:#d32f2f;">请选择要导入的表！</span>';
        return;
      }
      if (!fileInput.files || fileInput.files.length === 0) {
        importResult.innerHTML = '<span style="color:#d32f2f;">请选择Excel文件！</span>';
        return;
      }
      const file = fileInput.files[0];
      const formData = new FormData();
      formData.append('table', table);
      formData.append('file', file);
      importResult.innerHTML = '<span style="color:#388e3c;">正在导入，请稍候...</span>';
      try {
        const res = await fetch('/api/import', {
          method: 'POST',
          headers: { 'Authorization': sessionStorage.getItem('token') || '' },
          body: formData
        });
        const data = await res.json();
        if (res.ok) {
          importResult.innerHTML = '<span style="color:#388e3c;">导入成功，共导入 '+(data.count||0)+' 条数据！</span>';
        } else {
          importResult.innerHTML = '<span style="color:#d32f2f;">导入失败：'+(data.error||'数据字段不符合')+'</span>';
        }
      } catch (err) {
        importResult.innerHTML = '<span style="color:#d32f2f;">导入失败，服务器异常</span>';
      }
    };
  }
}); 